package com.study.web;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * @author study
 * @version 1.0
 * @date 2020/6/10 20:30
 * 显示图片
 */
@RestController
@RequestMapping("show")
public class ShowPicController {
    private static final Logger log = LoggerFactory.getLogger(ShowPicController.class);

    private static final String PIC_FORMAT = "pic/%02d.jpg";

    @GetMapping("/pic/{id}")
    public void showPic(HttpServletResponse response, @PathVariable(name = "id") Integer id) {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        //TODO SpringBoot 获取资源文件路劲|https://blog.csdn.net/napoay/article/details/81048724|
        // 打成jar包获取文件有问题(https://blog.csdn.net/cscscssjsp/article/details/84822706)
        String format = String.format(PIC_FORMAT, id);
        System.out.println(format);
        InputStream stream = classLoader.getResourceAsStream(format);
        URL resource = classLoader.getResource(format);
        System.out.println(resource);
        try {
            System.out.println(stream);
            IOUtils.copy(stream, response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/pics/{id}")
    public void showPics(HttpServletResponse resp, @PathVariable(name = "id") Integer id) throws IOException {
        //TODO 打包后有个单独的config存放 文件
        log.info("查找的picidss   s  {}", id);
        String format = String.format(PIC_FORMAT, id);
        ClassPathResource resource = new ClassPathResource(format);
        System.out.println(new ClassPathResource("/").getFile());
        System.out.println(resource.getFile());
        try {
            IOUtils.copy(FileUtils.openInputStream(resource.getFile()), resp.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
